package view;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

import battleModel.Tank;

/**
 * 
 * @author Kyle Bush
 * 
 */
@SuppressWarnings("serial")
public class LoadView extends MasterViewPanel {

	private String background = "images/backgrounds/campaignMenu.png";
	private String gameList = "savedGames/gameList.txt";
	private BufferedImage img;
	private float alpha;
	private boolean fade;

	private GameButton btnNewGame, btnLoadGame, btnBack;

	private DefaultListModel savedGameList;
	private JList list;

	public LoadView(MasterView m) {
		super(m);

		setUpLayout();
		setUpButtons();
		setUpList();
		drawBackGround();

		alpha = 1.0f;
		fade = true;

		javax.swing.Timer myTimer = new javax.swing.Timer(15,
				new ActionListener() {
					public void actionPerformed(ActionEvent evt) {

						if (alpha <= 1.0 && !fade) {
							alpha += 0.005f;
							if (alpha >= 1.0) {
								alpha = 1.0f;
								fade = true;
							}
							// System.out.println("Not Fading");
							repaint();
						} else if (alpha > .6 && fade) {
							alpha -= 0.005f;
							if (alpha <= .6)
								fade = false;
							// System.out.println("Fading");
							repaint();
						}
					}
				});

		myTimer.start();
	}

	private void setUpLayout() {
		this.setLayout(null);
		this.setOpaque(false);
	}

	private void setUpButtons() {

		// New Game Button
		btnNewGame = new GameButton(m.getIcon("newGame"), m.getIcon("newGameS"));
		btnNewGame.setMenuButton();
		btnNewGame.setListener(new NewGameListener());
		this.add(btnNewGame);

		// Load Game Button
		btnLoadGame = new GameButton(m.getIcon("loadGame"),
				m.getIcon("loadGameS"));
		btnLoadGame.setMenuButton();
		btnLoadGame.setDisabledIcon(m.getIcon("loadD"));
		btnLoadGame.setListener(new LoadGameListener());
		this.add(btnLoadGame);

		// Back to main menu button
		btnBack = new GameButton(m.getIcon("mainMenu"), m.getIcon("mainMenuS"));
		btnBack.setMenuButton();
		btnBack.setListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				m.changeView(Views.MENU, null);
			}
		});

		this.add(btnBack);

		// Button Positioning
		for (int i = 0; i < this.getComponentCount(); i++) {
			this.getComponent(i).setLocation(555, 347 + (75 * i));
		}
	}

	private void setUpList() {

		// List Header
		JLabel listTitle = new JLabel("SAVED GAMES");
		listTitle.setFont(new Font("Stencil", Font.PLAIN, 40));
		listTitle.setForeground(Color.WHITE);
		listTitle.setSize(260, 60);
		listTitle.setLocation(25, 120);
		this.add(listTitle);

		savedGameList = new DefaultListModel();

		// Fill list with saved games
		try {
			Scanner readFile = new Scanner(new File(gameList));
			while (readFile.hasNext()) {
				savedGameList.addElement(readFile.nextLine());
			}
		} catch (FileNotFoundException e) {
		}

		// JList transparency
		list = new JList(savedGameList);
		list.setOpaque(false);
		list.setBorder(BorderFactory.createEmptyBorder());

		// Text Options
		list.setFont(new Font("New Times Roman", Font.PLAIN, 20));
		list.setForeground(Color.WHITE);
		list.setSelectionForeground(Color.CYAN);

		// Set List Background Color (transparent)
		list.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.0f));
		list.setSelectionForeground(Color.WHITE);
		list.setSelectionBackground(new Color(0.1f, 0.1f, 0.1f, 0.5f));

		if (savedGameList.size() == 0) {
			savedGameList.addElement("No Saved Games Found");
			list.setEnabled(false);
			btnLoadGame.setEnabled(false);
		}

		// ScrollPane transparency
		JScrollPane scrollpane = new JScrollPane(list);
		scrollpane.setSize(260, 400);
		scrollpane.setLocation(25, 175);
		scrollpane.setOpaque(false);
		scrollpane.getViewport().setOpaque(false);

		this.add(scrollpane);
	}

	private void drawBackGround() {

		try {
			img = ImageIO.read(new File(background));
		} catch (IOException e) {
			e.printStackTrace();
		}
		repaint();
	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		Graphics2D g2d = (Graphics2D) g;

		// set the opacity
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
				alpha));
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);

		g.drawImage(img, 0, 0, this);

		// increase the opacity and repaint
		alpha += 0.03f;
		if (alpha >= 1.0f) {
			alpha = 1.0f;
		} else {
			repaint();
		}

		// sleep for a bit
		try {
			Thread.sleep(5);
		} catch (InterruptedException e) {

			e.printStackTrace();
		}
	}

	private class NewGameListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			m.changeView(Views.CAMPAIGN, null);
		}

	}

	private class LoadGameListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {

			// If there is a selected saved game
			if (list.getSelectedIndex() >= 0) {

				String fileName = (String) savedGameList.getElementAt(list
						.getSelectedIndex()) + ".dat";

				System.out.println("Load Game File: " + fileName);
				try {
					FileInputStream fis = new FileInputStream("savedGames/"
							+ fileName); 
					
					ObjectInputStream in = new ObjectInputStream(fis);

					Tank playerTank = (Tank) in.readObject();

					in.close();
					fis.close();

					m.changeView(Views.BATTLE, playerTank);
				} catch (FileNotFoundException fnfe) {
					JOptionPane.showMessageDialog(null,
							"File Not Found Loading", "Error",
							JOptionPane.INFORMATION_MESSAGE, null);
					return;
				} catch (IOException ioe) {
					JOptionPane.showMessageDialog(null, "IO Exception");
					ioe.printStackTrace();
				} catch (ClassNotFoundException cnfe) {
					JOptionPane.showMessageDialog(null,
							"Class not found Exception");
					cnfe.printStackTrace();
				}
			}
		}

	}

	/**
	 * String representation of panel name.
	 */
	public String toString() {
		return "LOAD";
	}

}
